package uu.tools.edge;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Commander {
    public static Map<String, String> parse(String commandLine) {
        List<String> args = parseCommandLine(commandLine);
        Map<String, String> map = new HashMap<>();
        boolean waitValue = false;
        String key = null;
        for (String arg : args) {
            if (waitValue) {
                waitValue = false;
                map.put(key, arg);
            } else if (arg.startsWith("-")) {
                waitValue = true;
                key = arg;
            } else {
                map.put(arg, "");
            }
        }
        return map;
    }

    private static List<String> parseCommandLine(String commandLine) {
        List<String> args = new ArrayList<>();
        boolean insideQuotes = false;
        boolean escapeQuote = false;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < commandLine.length(); i++) {
            char c = commandLine.charAt(i);
            if (escapeQuote) {
                escapeQuote = false;
                if (c == '\\') {
                    sb.append("\\");
                } else if (c == 'n') {
                    sb.append("\n");
                } else if (c == '\"') {
                    sb.append("\"");
                } else {
                    sb.append("\\");
                    sb.append(c);
                }
            } else if (c == '\\') {
                escapeQuote = true;
            } else if (c == '\"') {
                insideQuotes = !insideQuotes;
            } else if (c == ' ' && !insideQuotes) {
                if (sb.length() > 0) {
                    args.add(sb.toString());
                    sb = new StringBuilder();
                }
            } else {
                sb.append(c);
            }
        }
        if (sb.length() > 0) {
            args.add(sb.toString());
        }
        return args;
    }
}
